import { NestApplication, NestFactory } from "@nestjs/core";
import { Logger, VersioningType, VERSION_NEUTRAL } from "@nestjs/common";
import { JwtUserMiddleware } from "./auth/guard/jwt/auth.jwt.middleware";
import { ConfigService } from "@nestjs/config";
import { AppModule } from "./app.module";
import setupSwagger from "./setup.swagger";

async function bootstrap() {
  const app: NestApplication = await NestFactory.create(AppModule);
  const configService = app.get(ConfigService);
  const env: string = configService.get<string>("app.env");
  const tz: string = configService.get<string>("app.timezone");
  const host: string = configService.get<string>("app.http.host");
  const port: number = configService.get<number>("app.http.port");
  const versioning: boolean = configService.get<boolean>("app.versioning");
  const swagger: boolean = configService.get<boolean>("app.swagger");

  const logger = new Logger();
  process.env.TZ = tz;
  process.env.NODE_ENV = env;

  // Global Prefix
  app.setGlobalPrefix("/api");

  // global jwt guard
  app.use(new JwtUserMiddleware().use)

  // Versioning
  if (versioning) {
    await app.enableVersioning({
      type: VersioningType.URI,
      defaultVersion: VERSION_NEUTRAL,
    });
  }

  // swagger enable
  if(swagger) { await setupSwagger(app) }

  // Listen
  await app.listen(port, host);

  logger.log(`==========================================================`);
  logger.log(`App Environment is ${env}`, "NestApplication");
  logger.log(`App Language is ${configService.get<string>("app.language")}`, "NestApplication");
  logger.log(`App Debug is ${configService.get<boolean>("app.debug")}`, "NestApplication");
  logger.log(`App Versioning is ${versioning}`, "NestApplication");
  logger.log(`App Timezone is ${tz}`, "NestApplication");

  logger.log(`==========================================================`);

  if(swagger) logger.log(`🚀 Documentation: http://localhost:${port}/documentation`, "NestApplication");
  logger.log(`🚀 Server running on ${await app.getUrl()}`, "NestApplication");

  logger.log(`==========================================================`);
}
bootstrap();
